import type { Context } from 'koa';
import { IsNotEmpty } from 'class-validator';
import { ActivityService } from '@/services/activity';
import { ChatService } from '@/services/chat';
import { ResponseErrors } from '@/enums/responseErrors';

class ParticipateDto {
  @IsNotEmpty()
  activityId: string = undefined;
}

// 检查活动是否存在
export const activityParticipateController = async (ctx: Context) => {
  const uid = ctx.userId;
  const input = ctx.request.body;
  const { activityId } = await ctx.vailParams<ParticipateDto>(ParticipateDto, input);

  // 检查该活动是否存在
  const activity = await ActivityService.getActivityById(activityId);
  if (!activity) {
    ctx.sendError(ResponseErrors.activityNotExist);
    return;
  }

  const payload = { activityId, userId: uid };

  // 检查当前用户是否已参与过该活动
  const participated = await ActivityService.checkUserParticipated(payload);

  if (participated) {
    ctx.sendError(ResponseErrors.userParticipatedActivity);
    return;
  }
  // 参与活动
  const result = await ActivityService.userParticipateActivity(payload);

  // 加入聊天室
  await ChatService.addUsersTochatRoom({
    roomId: activity.chatRoom,
    users: [uid]
  })

  ctx.sendSuccess({ id: result._id });
}

// 参与